import base64
import random
import requests
import time
from markdown import markdown

from anti_useragent import UserAgent
from django.contrib.auth import authenticate, login, logout
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.core.mail import send_mail
from jsonpath import jsonpath
from lxml import etree

from ..froms import LoginForm, RegisterForm, ArticleForm, CommentForm, EditpasswordForm, FeedbackForm
from ..models import UserInfo, NewsData, Articles, Tags, Category, Cover, Comment, Avatars, Feedback, Menu, Site, MyInfo
from ..static.plugin.captcha1.captcha import ValidCodeImg
from ..static.plugin.sub_comment.sub_comment import sub_comment, Serialization_comment, computeCommentNumber


# 用来中登录和注册中获取错误信息
def error_data(form):
    """
    :param form: 表单实例对象
    :return: 第一个错误信息名字,第一个错误信息
    """
    error_list = list(form.errors.keys())
    error_name = error_list[0]  # 第一个错误信息名字
    error_value = form.errors[error_name][0]  # 第一个错误信息
    return error_name, error_value


# 获取网站信息
def websiteinfo(request):
    site = Site.objects.all().first()
    my_info = MyInfo.objects.all().first()
    data = {
        'title': site.title,  # 标题
        'create_date': str(site.create_date)[0:10],  # 建站日期
        'version': site.version,  # 网站版本号
        'icon': site.icon.url,  # 网站图标
        'article_number': len(Articles.objects.all()),  # 文章数量
        'online_users': len(request.ip_list),  # 在线人数
        'email': my_info.email,  # 邮箱号
        'github_url': my_info.github_url,  # git链接
        'wechat_img': my_info.wechat_img.url,  # 微信图片
        'qq_img': my_info.qq_img.url  # qq图片
    }
    return JsonResponse({
        'code': 200,
        'data': data
    })


# 登录
def Login(request):
    state = {  # 返回给前端的数据
        'code': 200,  # 表示验证码是否正确，True表示正确
        'error': '登录成功',  # 表示验证之后的提示信息
        'self': None,  # 表示错误的对象
    }
    if request.method == 'POST':
        body = eval(request.body.decode('utf-8'))
        form = LoginForm(body['userData'])
        if not form.is_valid():
            state['code'] = 404
            state['self'], state['error'] = error_data(form)
            return JsonResponse(state)
        # 使用django自带的用户系统authenticate进行登录处理
        user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
        if not user:  # 登录失败
            state['isright'] = 404
            state['self'] = 'password1'
            state['error'] = '用户名或者密码输入错误'
            return JsonResponse(state)
        else:  # 登录成功
            state['userinfo'] = {
                'nid': user.nid,
                'username': user.username,
                'email': user.email,
                'is_superuser': user.is_superuser,
                'last_login': str(user.last_login)[0:19],
                'date_joined': str(user.date_joined),
                'sign_status': user.get_sign_status_display(),
                'account_status': user.get_account_status_display(),
                'avatar_url': user.avatar.url.url
            }
            login(request, user)  # 保存会话
            request.session.set_expiry(60 * 60 * 24 * 5)  # 设置会话有效时间
            return JsonResponse(state)
    return JsonResponse({})


# 注册
def register(request):
    state = {  # 返回给前端的数据
        'code': 200,  # 表示验证码是否正确，True表示正确
        'error': '注册成功',  # 表示验证之后的提示信息
        'self': None,  # 表示错误的对象
    }
    if request.method == 'POST':
        data = eval(request.body.decode('utf-8'))['userData']  # 获取输入的数据，data由中间件添加
        form = RegisterForm(data, request=request)
        if not form.is_valid():  # 如果不通过
            state['code'] = 404
            state['self'], state['error'] = error_data(form)
            return JsonResponse(state)
        # 使用django自带的用户系统添加用户
        UserInfo.objects.create_user(username=form.cleaned_data['username'],
                                     email=form.cleaned_data['mail'],
                                     password=form.cleaned_data['password1'],
                                     avatar_id=random.randint(1, 3))  # 封面从id1到3之间随机获取
        # 使用django自带的用户系统authenticate进行登录处理
        user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
        login(request, user)
        request.session.set_expiry(60 * 60 * 24 * 5)  # 设置会话有效时间
        state['userinfo'] = {
            'nid': user.nid,
            'username': user.username,
            'email': user.email,
            'is_superuser': user.is_superuser,
            'last_login': str(user.last_login)[0:19],
            'date_joined': str(user.date_joined),
            'sign_status': user.get_sign_status_display(),
            'account_status': user.get_account_status_display(),
            'avatar_url': user.avatar.url.url
        }
        return JsonResponse(state)
    return JsonResponse({})


# 注销登录
def Logout(request):
    logout(request)  # 使用django自带的注销APL
    state = {  # 返回给前端的数据
        'code': 200,  # 表示验证码是否正确，True表示正确
    }
    return JsonResponse(state)


# 获取验证码
def getCode(request):
    # print(time.time())
    last_data = NewsData.objects.last()
    last_time = time.strptime(str(last_data.creation_time)[0:18], '%Y-%m-%d %X')
    last_time = time.mktime(last_time)
    print(time.time() - last_time)
    code = ValidCodeImg(width=120, height=40)
    img, data = code.getValidCodeImg()
    request.session['code'] = data  # 存储验证码的值到会话中
    request.session.set_expiry(60)  # 会话的有效时间为60
    imgdata = str(base64.b64encode(img).decode('utf-8'))
    return JsonResponse({'img': imgdata})


# 判断是否获取爬虫数据，一个小时内不能获取
def is_get_news(type):
    last_data = NewsData.objects.filter(type=type).last()
    if not last_data:
        return True
    last_time = time.strptime(str(last_data.creation_time)[0:18], '%Y-%m-%d %X')
    last_time = time.mktime(last_time)
    a = int(time.time() - last_time)
    if a >= 3600.0:
        return True
    return False


# 爬取微博热门榜
def weibo(request):
    is_send = is_get_news(0)
    if is_send:
        headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.71"
        }
        response = requests.get('https://weibo.com/ajax/statuses/hot_band', headers=headers)
        if response.status_code == 200:
            json_data = response.json()
            json_data = jsonpath(json_data, '$..band_list')
            item_list = []
            for item in json_data[0]:
                try:
                    item_dict = {'id': jsonpath(item, '$.onboard_time')[0],
                                 'title': jsonpath(item, '$.word')[0],
                                 'link': f'https://s.weibo.com/weibo?q=%23{jsonpath(item, "$.word")[0]}%23',
                                 'info': '热度:' + str(jsonpath(item, '$.num')[0])}
                    item_list.append(item_dict)
                except TypeError:
                    continue
                NewsData.objects.create(title=item_dict['title'],
                                        link=item_dict['link'],
                                        info=item_dict['info'],
                                        type=0)
        else:
            data_list = list(NewsData.objects.filter(type=0))[-1:-51:-1]
            item_list = []
            for item in data_list:
                item_dict = {
                    'id': item.id,
                    'title': item.title,
                    'link': item.link,
                    'info': item.info
                }
                item_list.append(item_dict)
    else:
        data_list = list(NewsData.objects.filter(type=0))[-1:-51:-1]
        item_list = []
        for item in data_list:
            item_dict = {
                'id': item.id,
                'title': item.title,
                'link': item.link,
                'info': item.info
            }
            item_list.append(item_dict)
    return JsonResponse({'title': '微博', 'data': item_list})


# 爬取知乎热门榜
def zhihu(request):
    is_send = is_get_news(1)
    if is_send:
        headers = {
            "user-agent": UserAgent().chrome
        }
        response = requests.get('https://www.zhihu.com/api/v4/creators/rank/hot?domain=0&period=day', headers=headers)
        json_data = response.json()
        json_data = jsonpath(json_data, '$.data')[0]
        item_list = []
        for item in json_data:
            item_dict = {
                'id': jsonpath(item, '$.question.id')[0],
                'title': jsonpath(item, '$.question.title')[0],
                'link': jsonpath(item, '$..question.url')[0],
                'info': '被浏览:' + str(jsonpath(item, '$.reaction.pv')[0])
            }
            item_list.append(item_dict)
            NewsData.objects.create(title=item_dict['title'],
                                    link=item_dict['link'],
                                    info=item_dict['info'],
                                    type=1)
    else:
        data_list = list(NewsData.objects.filter(type=1))[-1:-51:-1]
        item_list = []
        for item in data_list:
            item_dict = {
                'id': item.id,
                'title': item.title,
                'link': item.link,
                'info': item.info
            }
            item_list.append(item_dict)
    return JsonResponse({'title': '知乎', 'data': item_list})


# 爬取微信热门榜
def weixin(request):
    is_send = is_get_news(2)
    if is_send:
        headers = {
            "user-agent": UserAgent(platform='windows').chrome
        }
        response = requests.get('https://tophub.today/n/WnBe01o371', headers=headers)
        response.encoding = response.apparent_encoding
        html = etree.HTML(response.text)
        tr_list = html.xpath('//table[1]//tr')[0:25]
        item_list = []
        for item in tr_list:
            item_dict = {
                'id': item.xpath('td[@align="center"]/text()')[0][0:-1],
                'title': item.xpath('td[@class="al"]/a/text()')[0],
                'link': "https://tophub.today" + item.xpath('td[@class="al"]/a/@href')[0],
                'info': item.xpath('td[last()-1]/text()')[0]
            }
            item_list.append(item_dict)

            NewsData.objects.create(title=item_dict['title'],
                                    link=item_dict['link'],
                                    info=item_dict['info'],
                                    type=2)
    else:
        data_list = list(NewsData.objects.filter(type=2))[-1:-51:-1]
        item_list = []
        for item in data_list:
            item_dict = {
                'id': item.id,
                'title': item.title,
                'link': item.link,
                'info': item.info
            }
            item_list.append(item_dict)
    return JsonResponse({'title': '微信', 'data': item_list})


# 爬取百度热门榜
def baidu(request):
    is_send = is_get_news(3)
    if is_send:
        headers = {
            "user-agent": UserAgent(platform='windows').chrome
        }
        response = requests.get('https://top.baidu.com/board?tab=realtime', headers=headers)
        response.encoding = response.apparent_encoding
        html = etree.HTML(response.text)
        div_list = html.xpath('//div[contains(@class,"category-wrap_iQLoo")]')
        id = 0
        item_list = []
        for item in div_list[1:]:
            id += 1
            item_dict = {
                'id': id,
                'title': item.xpath('div[@class="content_1YWBm"]/a/div/text()')[0],
                'link': item.xpath('div[@class="content_1YWBm"]/a/@href')[0],
                'info': '热搜指数：' + str(
                    item.xpath('div[contains(@class,"trend_2RttY")]/div[@class="hot-index_1Bl1a"]/text()')[0])
            }
            NewsData.objects.create(title=item_dict['title'],
                                    link=item_dict['link'],
                                    info=item_dict['info'],
                                    type=3)
    else:
        data_list = list(NewsData.objects.filter(type=3))[-1:-51:-1]
        item_list = []
        for item in data_list:
            item_dict = {
                'id': item.id,
                'title': item.title,
                'link': item.link,
                'info': item.info
            }
            item_list.append(item_dict)
    return JsonResponse({'title': '百度', 'data': item_list})


# 全部文章
def ArticleAll(request):
    articles_all = Articles.objects.filter(status=1)
    pag = request.GET.get('pag', 1)
    paginator = Paginator(articles_all, 10)
    articles_list = paginator.get_page(pag)
    item_list = []
    for item in articles_list:
        item_dict = {
            'nid': item.nid,
            'title': item.title,
            'abstract': item.abstract,
            'create_date': str(item.create_date)[0:16],
            'cover_url': item.cover.url.url,
            'look_count': item.look_count,
            'comment_count': item.comment_count,
            'digg_count': item.digg_count,
            'collects_count': item.collects_count,
            'link': item.link
        }
        item_list.append(item_dict)
    return JsonResponse({
        'code': 200,
        'article_info': item_list,
        'num_pages': paginator.num_pages,  # 总页数
        'total': paginator.count,  # 总条目
        'current_page': articles_list.number,  # 当前页数
    })


# 文章搜索
def search(request):
    if request.method == 'POST':
        data = eval(request.body.decode())
        key = data.get('key')  # 关键字
        words = data.get('words')  # 字数
        pag = data.get('pag', 1)  # 分页
        # 用于字数筛选的字典
        word_dict = {
            'words2': (0, 100),  # 100以内
            'words3': (0, 500),  # 500以内
            'words4': (0, 1000),  # 1000以内
            'words5': (0, 3000),  # 3000以内
            'words6': (0, 5000),  # 5000以内
            'words7': (0, 10000),  # 10000以内
            'words8': '10000',  # 10000以上
        }
        sort = data.get('sort')  # 排序方法
        # 用于排序方法的字典
        sort_dict = {
            'sort1': '-nid',  # 综合排序
            'sort2': '-look_count',  # 最多点击
            'sort3': '-change_date',  # 最新发布
            'sort4': '-comment_count',  # 最多评论
            'sort5': '-collects_count'  # 最多收藏
        }
        category = data.get('category')  # 分类
        # 用于分类的字典
        category_dict = {
            'category2': 1,  # 后端
            'category3': 2,  # 前端
            'category4': 3  # 数据库
        }
        # 用来表示查询条件的字典
        search_condition = {
            'title__contains': key,
            'status': 1,
        }
        # 字数处理
        if words in list(word_dict.keys())[0:6]:
            search_condition['word__range'] = word_dict[words]
        elif words == 'words8':
            search_condition['word__gt'] = word_dict[words]
        # 分类处理
        if category != 'category1':
            search_condition['category__id'] = category_dict[category]
        articles = Articles.objects.filter(**search_condition).order_by(sort_dict[sort])
        paginator = Paginator(articles, 10)
        articles = paginator.get_page(pag)
        item_list = []
        for item in articles.object_list:
            item_dict = {
                'nid': item.nid,
                'title': item.title,
                'change_date': str(item.change_date)[0:10],
                'cover': item.cover.url.url,
                'look_count': item.look_count,
            }
            item_list.append(item_dict)
        return JsonResponse({
            'code': 200,
            'articles': item_list,
            'total': paginator.count,  # 总条目
            'current_page': articles.number,  # 当前页数
            'num_pages': paginator.num_pages,  # 总页数
        })
    return JsonResponse({})


# 每日推荐
def ArticleRecommend(request):
    aecommend_Article = Articles.objects.filter(status=1).order_by('look_count')[0:6]
    item_list = []
    for item in aecommend_Article:
        item_dict = {
            'nid': item.nid,
            'title': item.title,
            'abstract': item.abstract,
            'create_date': str(item.create_date)[0:16],
            'cover_url': item.cover.url.url,
            'link': item.link
        }
        item_list.append(item_dict)
    return JsonResponse({
        'aecommend_Article': item_list
    })


# 文章详情
def article(request, nid):
    articles = Articles.objects.filter(nid=nid).first()
    usernid = request.GET.get('usernid')  # 用户id
    user = UserInfo.objects.filter(nid=usernid).first()
    error = {
        'code': 200,
    }
    if articles:
        # 获取标签列表
        tags = articles.tag.all()
        tags_list = []
        for i in tags:
            tags_dict = {
                'nid': i.nid,
                'title': i.title
            }
            tags_list.append(tags_dict)
        articles_dict = {
            'nid': articles.nid,
            'title': articles.title,
            'content': articles.content,
            'change_date': str(articles.change_date)[0:10],
            'status': articles.get_status_display(),
            'cover_url': articles.cover.url.url,
            'cover': articles.cover.nid,
            # 封面对象
            'fileList': [{
                'name': articles.cover.nid,
                'url': '/api' + articles.cover.url.url,
            }],
            'tag': tags_list,
            'user': articles.user.username,
            'usernid': articles.user.nid,
            'abstract': articles.abstract,
            'like': articles.digg_count,  # 点赞数
            'islike': False,  # 是否喜欢，默认为不喜欢
            'collect': articles.collects_count,  # 收藏数
            'iscollect': False,  # 是否收藏，默认为没有收藏
            'comment': articles.comment_count,  # 评论数
        }
        category = articles.category.all()
        if category:
            articles_dict['category'] = category.first().id
        # 如果获取到用户信息的话，则获取是否喜欢或者收藏
        if user:
            if articles in user.like.all():
                articles_dict['islike'] = True
            if articles in user.collects.all():
                articles_dict['iscollect'] = True
        error['articles'] = articles_dict
        # 如果当前请求用户不是文章作者的话，则浏览数+1
        if int(usernid) != int(articles.user.nid):
            articles.look_count += 1
            articles.save()
        return JsonResponse(error)
    error['code'] = 404
    error['info'] = '文章不存在'
    return JsonResponse(error)


# 获取文章评论
def articleComment(request, nid):
    error = {
        'code': 200
    }
    if Articles.objects.filter(nid=nid).exists():
        comment_list = sub_comment(nid)  # 获取评论内容
        error['comment'] = Serialization_comment(comment_list)
        return JsonResponse(error)
    error['code'] = 404
    return JsonResponse(error)


# 我的文章列表
def MyArticle(request, nid):
    error = {
        'code': 200,
    }
    articles = Articles.objects.filter(user__nid=nid)
    pag = request.GET.get('pag', 1)
    paginator = Paginator(articles, 10)
    articles = paginator.get_page(pag)
    if nid == request.user.nid:
        item_list = []
        for item in articles:
            item_dict = {
                'nid': item.nid,
                'title': item.title,
                'user': item.user.username,
                'status': item.get_status_display(),
                'look_count': item.look_count,
                'comment_count': item.comment_count,
                'digg_count': item.digg_count,
                'collects_count': item.collects_count,
                'change_date': str(item.create_date)[0:16],
            }
            item_list.append(item_dict)
        error['articles'] = item_list
        error['num_pages'] = paginator.num_pages  # 当前页数
        error['total'] = paginator.count  # 总条目
        error['current_page'] = articles.number  # 总条目
        return JsonResponse(error)
    error['info'] = '请求错误'
    error['code'] = 404
    return JsonResponse(error)


# 我的喜欢文章列表
def MyArticleLike(request, nid):
    error = {
        'code': 200,
    }
    user = UserInfo.objects.filter(nid=nid).first()
    if user:
        like_article = user.like.all()  # 需要分页处理的数据
        pag = request.GET.get('pag', 1)
        paginator = Paginator(like_article, 10)
        like_article = paginator.get_page(pag)
        item_list = []
        for item in like_article:
            item_dict = {
                'nid': item.nid,
                'title': item.title,
                'user': item.user.username,
                'status': item.get_status_display(),
                'look_count': item.look_count,
                'comment_count': item.comment_count,
                'digg_count': item.digg_count,
                'collects_count': item.collects_count,
                'change_date': str(item.create_date)[0:16],
            }
            item_list.append(item_dict)
        error['articles'] = item_list
        error['num_pages'] = paginator.num_pages  # 当前页数
        error['total'] = paginator.count  # 总条目
        error['current_page'] = like_article.number  # 总条目
        return JsonResponse(error)
    error['articles'] = '用户不存在'
    error['code'] = 404
    return JsonResponse(error)


# 我的收藏文章列表
def MyArticleCollect(request, nid):
    error = {
        'code': 200,
    }
    user = UserInfo.objects.filter(nid=nid).first()
    if user:
        collects_article = user.collects.all()  # 需要分页处理的数据
        pag = request.GET.get('pag', 1)
        paginator = Paginator(collects_article, 10)
        collects_article = paginator.get_page(pag)
        item_list = []
        for item in collects_article:
            item_dict = {
                'nid': item.nid,
                'title': item.title,
                'user': item.user.username,
                'status': item.get_status_display(),
                'look_count': item.look_count,
                'comment_count': item.comment_count,
                'digg_count': item.digg_count,
                'collects_count': item.collects_count,
                'change_date': str(item.create_date)[0:16],
            }
            item_list.append(item_dict)
        error['articles'] = item_list
        error['num_pages'] = paginator.num_pages  # 当前页数
        error['total'] = paginator.count  # 总条目
        error['current_page'] = collects_article.number  # 总条目
        return JsonResponse(error)
    error['info'] = '用户不存在'
    error['code'] = 404
    return JsonResponse(error)


# 文章搜索
def articleSearch(request):
    global articles
    data = request.GET
    condition = {}
    user = UserInfo.objects.filter(nid=data['usernid']).first()
    if data['articlesType'] == '1':
        articles = Articles.objects.filter(user__nid=data['usernid'])
    elif data['articlesType'] == '2':
        articles = user.like.all()
    elif data['articlesType'] == '3':
        articles = user.collects.all()
    if data['state']:
        condition['status'] = data['state']
    if data['key']:
        condition['title__contains'] = data['key']
    if data['tag']:
        condition['tag__nid'] = data['tag']
    if data['start_time'] and data['end_time']:
        condition['change_date__range'] = (data['start_time'], data['end_time'])
    articles = articles.filter(**condition)  # 分页之前的数据
    pag = data.get('pag', 1)  # 获取请求分页数
    paginator = Paginator(articles, 10)
    articles = paginator.get_page(pag)
    item_list = []
    for item in articles:
        item_dict = {
            'nid': item.nid,
            'title': item.title,
            'user': item.user.username,
            'status': item.get_status_display(),
            'look_count': item.look_count,
            'comment_count': item.comment_count,
            'digg_count': item.digg_count,
            'collects_count': item.collects_count,
            'change_date': str(item.create_date)[0:16],
        }
        item_list.append(item_dict)
    return JsonResponse({
        'code': 200,
        'articles': item_list,
        'num_pages': paginator.num_pages,  # 当前页数
        'total': paginator.count,  # 总条目
        'current_page': articles.number,  # 总条目
    })


# 获取文章标签和分类、封面等信息，用于文章添加和编辑时的选择
def getarticleinfo(request):
    tags = Tags.objects.all()[0:3]
    categorys = Category.objects.all()[0:3]
    covers = Cover.objects.all()[0:3]
    tags_list = []
    category_list = []
    cover_list = []
    for tag in tags:
        tag_obj = {
            'id': str(tag.nid),
            'title': tag.title
        }
        tags_list.append(tag_obj)
    for category in categorys:
        category_obj = {
            'id': category.id,
            'title': category.title
        }
        category_list.append(category_obj)
    for cover in covers:
        cover_obj = {
            'id': cover.nid,
            'url': '/api' + cover.url.url
        }
        cover_list.append(cover_obj)
    return JsonResponse({
        'tags': tags_list,
        'category': category_list,
        'cover': cover_list
    })


# 添加文章
def addarticle(request):
    if request.method == 'POST':
        error = {
            'code': 200,
            'info': '发布成功'
        }
        data = eval(request.body.decode('utf-8'))
        form = ArticleForm(data=data, request=request)
        if not form.is_valid():
            error_name, error_value = error_data(form)
            error['code'] = 404
            error['info'] = error_value
            return JsonResponse({'value': error})
        # 发布文章或者第一次保存文章
        if data.get('id', -1) == -1:
            articles = Articles.objects.create(title=form.cleaned_data['title'],
                                               content=form.cleaned_data['content'],
                                               abstract=form.cleaned_data['abstract'],
                                               cover=Cover.objects.get(nid=form.cleaned_data['cover']),
                                               status=form.cleaned_data['status'],
                                               user_id=request.user.nid)
        # 不为-1则声明已经保存过一次了，有过保存记录的
        else:
            Articles.objects.filter(nid=data['id']).update(
                title=form.cleaned_data['title'],
                content=form.cleaned_data['content'],
                abstract=form.cleaned_data['abstract'],
                cover=Cover.objects.get(nid=form.cleaned_data['cover']),
                status=form.cleaned_data['status'],
            )
            articles = Articles.objects.filter(nid=data['id']).first()
            articles.tag.clear()
        # 循环添加标签
        if form.cleaned_data['tag']:
            for tag in form.cleaned_data['tag']:
                articles.tag.add(tag)
        if form.cleaned_data['category']:
            articles.category.add(form.cleaned_data['category'])
        html_content = markdown(form.cleaned_data['content'])  # 将markdown文本解析为html文本
        html = etree.HTML(html_content)  # 通过xpath获取里面的所有内容
        html_content_str = "".join(html.xpath('//*/text()')).replace('\n', '').replace('\t', '').replace(' ', '')
        articles.word = len(html_content_str)
        articles.save()
        error['id'] = articles.nid
        return JsonResponse(error)


# 删除文章
def delarticle(request, nid):
    error = {
        'info': '删除成功',
        'code': 200,
    }
    articles = Articles.objects.get(nid=nid)
    if articles.user.nid != request.user.nid:
        error['info'] = '删除失败'
        error['state'] = 404
        return JsonResponse(error)
    articles.delete()
    return JsonResponse(error)


# 上传封面
def addcover(request):
    img = request.FILES['file']
    cover = Cover.objects.create(url=img)
    request.session['img_id'] = cover.nid
    return JsonResponse({
        'code': 200,
        'info': '上传成功'
    })


# 添加或删除喜欢
def like(request):
    nid = request.GET.get('nid')
    userNid = request.GET.get('user')
    user = UserInfo.objects.filter(nid=userNid)
    articles = Articles.objects.get(nid=nid)
    error = {
        'code': 200,
        'info': '点赞成功！'
    }
    # 如果用户不存在，则需要登录
    if not user:
        error['code'] = 404
        error['info'] = '请先登录'
        return JsonResponse(error)
    like_all = user[0].like.all()
    # 如果存在，则删除喜欢
    if articles in like_all:
        error['info'] = '已取消点赞！'
        user[0].like.remove(articles)
        articles.digg_count -= 1
        articles.save()
        return JsonResponse(error)
    user[0].like.add(nid)
    articles.digg_count += 1
    articles.save()
    return JsonResponse(error)


# 添加或删除收藏
def collect(request):
    nid = request.GET.get('nid')
    userNid = request.GET.get('user')
    user = UserInfo.objects.filter(nid=userNid)
    articles = Articles.objects.get(nid=nid)
    error = {
        'code': 200,
        'info': '收藏成功！'
    }
    # 如果用户不存在，则需要登录
    if not user:
        error['code'] = 404
        error['info'] = '请先登录'
        return JsonResponse(error)
    collect_all = user[0].collects.all()
    # 如果存在，则删除收藏
    if articles in collect_all:
        error['info'] = '已取消收藏！'
        user[0].collects.remove(articles)
        articles.collects_count -= 1
        articles.save()
        return JsonResponse(error)
    user[0].collects.add(nid)
    articles.collects_count += 1
    articles.save()
    return JsonResponse(error)


# 添加评论
def addComment(request):
    if request.method == 'POST':
        data = eval(request.body.decode('utf-8'))
        error = {
            'code': 200,
            'info': '发布成功'
        }
        form = CommentForm(data)
        if not form.is_valid():
            name, error['info'] = error_data(form)
            error['code'] = 404
            return JsonResponse(error)
        create_dict = {
            'article_id': data['nid'],
            'user_id': data['user'],
            'content': data['content'],
        }
        # 获取父评论id
        root_comment = form.cleaned_data['rootComment']
        # 如果没有传父评论id则为-1,不为-1则声明是子评论
        if root_comment != -1:
            create_dict['parent_comment_id'] = root_comment
            # 获取该评论的父评论，该评论的子评论数+1
            comment = Comment.objects.get(nid=root_comment)
            comment.comment_count += 1
            comment.save()
        Comment.objects.create(**create_dict)
        articles = Articles.objects.get(nid=form.cleaned_data['nid'])
        articles.comment_count += 1
        articles.save()
        return JsonResponse(error)
    return JsonResponse({})


# 删除评论
def delComment(request):
    data = eval(request.body.decode('utf-8'))
    error = {
        'code': 200
    }
    comment = Comment.objects.get(nid=data['nid'])
    if comment.user.nid != data['user']:
        error['code'] = 404
        error['info'] = '删除失败'
        return JsonResponse(error)
    comment_count = 1  # 文章评论数，如果是有子评论的话，则需要加上该评论下的子评论个数
    # 如果该评论有子评论的话，则计算删除后的评论数
    if comment.parent_comment:
        root_comment_nid = comment.parent_comment.nid  # 该父评论的id
        root_comment = Comment.objects.get(nid=root_comment_nid)
        root_comment.comment_count = root_comment.comment_count - 1
        root_comment.save()
    number = computeCommentNumber(data['nid'], 0)
    comment_count += number
    articles_nid = comment.article_id
    comment.delete()
    articles = Articles.objects.get(nid=articles_nid)
    articles.comment_count = articles.comment_count - comment_count
    articles.save()
    return JsonResponse(error)


# 评论点赞
def likecomment(request):
    nid = request.GET.get('nid')  # 评论id
    error = {
        'code': 200,
        'info': '点赞成功'
    }
    comment = Comment.objects.filter(nid=nid).first()
    if comment:
        comment.digg_count += 1
        comment.save()
        return JsonResponse(error)
    error['code'] = 404
    return JsonResponse(error)


# 获取头像
def avatar(request):
    avatars = Avatars.objects.all()
    item_list = []
    for item in avatars:
        item_dict = {
            'id': item.nid,
            'url': item.url.url
        }
        item_list.append(item_dict)
    return JsonResponse({
        'code': 200,
        'avatars': item_list
    })


# 修改头像
def editavatar(request):
    if request.method == 'POST':
        error = {
            'info': '修改成功',
            'code': 200,
        }
        nid = eval(request.body.decode()).get('nid')
        avatars = Avatars.objects.filter(nid=nid)
        if not avatars:
            error['info'] = '修改失败'
            error['code'] = 404
            return JsonResponse(error)
        user = UserInfo.objects.get(nid=request.user.nid)
        print(user.avatar_id)
        user.avatar_id = avatars[0].nid
        user.save()
        return JsonResponse(error)
    return JsonResponse({})


# 获取用户信息
def userinfo(request):
    nid = request.GET.get('nid')
    user = UserInfo.objects.filter(nid=nid).first()
    json_data = {
        'nid': user.nid,
        'username': user.username,
        'email': user.email,
        'is_superuser': user.is_superuser,
        'last_login': str(user.last_login)[0:19],
        'date_joined': str(user.date_joined),
        'sign_status': user.get_sign_status_display(),
        'account_status': user.get_account_status_display(),
        'avatar_url': user.avatar.url.url
    }
    return JsonResponse({
        'code': 200,
        'data': json_data
    })


# 修改密码
def editpassword(request):
    if request.method == 'POST':
        data = eval(request.body.decode())
        error = {
            'info': '修改成功,请重新登录',
            'code': 200,
        }
        form = EditpasswordForm(data)
        # 如果验证失败
        if not form.is_valid():
            error['info'] = list(form.errors.values())[0][0]
            error['code'] = 404
            return JsonResponse(error)
        user = UserInfo.objects.get(nid=request.user.nid)
        user.set_password(form.cleaned_data['newPassword1'])
        user.save()
        return JsonResponse(error)
    return JsonResponse({})


# 意见反馈
def feedback(request):
    if request.method == 'POST':
        data = eval(request.body.decode())
        error = {
            'info': '反馈成功,管理员会尽快处理！',
            'code': 200
        }
        form = FeedbackForm(data)
        if not form.is_valid():
            error['info'] = list(form.errors.values())[0][0]
            error['code'] = 404
            return JsonResponse(error)
        Feedback.objects.create(**form.cleaned_data)
        superuser_user = UserInfo.objects.filter(is_superuser=1)
        superuser_email = []
        # 循环获取用于管理员权限的邮箱地址
        for item in superuser_user:
            superuser_email.append(item.email)
        # 向管理员用户发送提示信息
        send_mail(
            'Subject here',
            '您收到了一条反馈信息，请及时处理！',
            '1824376609@qq.com',
            superuser_email,
            fail_silently=False,
        )
        return JsonResponse(error)
    return JsonResponse({})


# 获取轮播图
def rotationimg(request):
    error = {
        'code': 200,
        'menu_time': 0,
        'menu_imt': []
    }
    type_ = request.GET.get('type')
    nid = request.GET.get('nid')  # 博客id
    item_list = []
    item_dict = {}
    # 如果博客id没有值的话，则说明不是文章详情
    if not nid:
        menu = Menu.objects.filter(nid=type_).first()
        menu_img = menu.menu_url.all()
        for item in menu_img:
            item_dict = {
                'nid': item.nid,
                'url': item.url.url
            }
            item_list.append(item_dict)
        error['menu_time'] = menu.menu_time
    else:
        articles = Articles.objects.filter(nid=nid).first()
        item_dict = {
            'nid': articles.cover.nid,
            'url': articles.cover.url.url
        }
        item_list.append(item_dict)
    error['menu_imt'] = item_list
    return JsonResponse(error)
